<template>
  <div>
    <CategorySelector style="margin-bottom:10px" :isDisable="!isShowAttrList"></CategorySelector>
    <el-card>
      <div v-if="isShowAttrList">
        <el-button type="primary" :icon="Plus" @click="toSaveAttrValue" :disabled="!categoryStore.category3Id">添加属性</el-button>
        <el-table :data="attrList" border style="margin-top:10px">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性名称" prop="attrName"></el-table-column>
          <el-table-column label="属性值列表" >
            <template v-slot="{row}">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" class="ml-2" type="success" style="margin-right:6px">{{attrValue.valueName}}</el-tag>
            </template>
          </el-table-column>
          
  <el-table-column label="操作">
    <template v-slot="{row}">
      <el-button title="修改" type="warning" size="small" :icon="Edit" @click="toEditAttr(row)" />
      <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF" title="真的确定要删除此条数据么?" @confirm="confirmEvent(row)">
        <template #reference>
          <el-button title="删除" type="danger" size="small" :icon="Delete" />
        </template>
      </el-popconfirm>
    </template>
</el-table-column>
        
        </el-table>
      </div>
      <div v-else>
        <el-form :model="attrInfo">
          <el-form-item label="属性名" style="width:300px">
            <el-input  placeholder="请输入属性名" v-model="attrInfo.attrName"  wdith="200px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="!attrInfo.attrName" @click="toAddAttrValue">添加属性值</el-button>
            <el-button type="default" @click="isShowAttrList=true">取消</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="attrInfo.attrValueList" style="margin-bottom:10px">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{row,$index}">
             <el-input size="small"  :ref="(input:any)=>inputRef[$index]=input"  v-model="row.valueName" v-show="row.isShowInput" placeholder="请输入属性值" @blur="toDeleteCurrentRow(row,$index)"></el-input>
             <span v-show="!row.isShowInput"   style="display:inline-block;width:100%" @dblclick="toEditAttrValue(row,$index)">{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
          <template v-slot="{row,$index}">
          <el-popconfirm confirm-button-text="确定"      cancel-button-text="取消" :icon="InfoFilled"      icon-color="#626AEF" title="真的要删除此条属性吗?" @confirm="confirmEventAttrValue($index)">
        <template #reference>
           <el-button title="删除属性" size="small" type="danger" :icon="Delete"></el-button>
        </template>
     </el-popconfirm>
  </template>

          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttrInfo" :disabled="!attrInfo.attrValueList.length">保存</el-button>
        <el-button type="default" @click="isShowAttrList=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import CategorySelector from '@/components/CategorySelector/index.vue'


export default {
  name: "Attr",
  components: {
    CategorySelector
  }
};
</script>

<script lang="ts" setup>

import {ref,watch,reactive, nextTick } from 'vue'
import { Plus, Edit, Delete,InfoFilled} from '@element-plus/icons-vue'
import {useCategoryListStore} from '@/stores/categoryList'
import{ reqGetAttrListData,reqDeleteAttrInfo,reqAddOrUpdateAttrInfo } from '@/api/product/attr'
import { ElMessage,type InputInstance } from 'element-plus';
import type { AttrInfoModel,AttrListModel, AttrValueInfoModel } from '@/api/model/attrModel'

const isShowAttrList = ref<boolean>(true)
const categoryStore=useCategoryListStore()
const attrList = ref<AttrListModel>([])
const inputRef = ref<InputInstance[]>([]);

//抽出来的属性对象，包含属性名和属性值
const attrInfo = reactive<AttrInfoModel>({
  attrName: '',
  attrValueList: [],
  categoryId: -1, // 对应的三级分类id
  categoryLevel: 3 // 等级 默认就是3
});

//获取属性列表的函数
const getAttrListData =async()=>{
   // 发送请求 获取三级分类下面对应的列表数据
  const{category1Id,category2Id,category3Id} = categoryStore
  const res = await reqGetAttrListData({category1Id,category2Id,category3Id})
  attrList.value = res
}
// 监视三级导航id，只有有了三级导航id,属性列表才可显示
watch(
  ()=>categoryStore.category3Id,
  async category3Id =>{
    // 没有三级导航id，就清空数组列表
    if(!category3Id){
      attrList.value = []
      return
    }
  // 获取属性列表数据
   getAttrListData()
},
  {immediate:true}  
)

// 单击确定,要真正的删除属性
const confirmEvent = async (row:any) => {
  await reqDeleteAttrInfo(row.id);
  // console.log('aar', result)
  // 提示用户删除成功
  ElMessage.success('删除属性成功了...');
  // 获取属性列表数据
  getAttrListData();
};

// 4. 取消删除属性
const cancelEvent = () => {
  console.log('cancel!');
};

// 添加属性值
const toAddAttrValue = ()=>{
  attrInfo.attrValueList.push({
    valueName:'',
    isShowInput:true
    })
    
    //输入框自动获得焦点
    nextTick(()=>{
      // inputRef.value?.focus()
      inputRef.value[attrInfo.attrValueList.length - 1].focus();

    });
}


    //失去焦点时，删除当前没有属性值的哪一项
    const toDeleteCurrentRow = (row:AttrValueInfoModel,index:number)=>{
      if(!row.valueName.trim()){
        // 没有值就删除当前项
        attrInfo.attrValueList.splice(index,1)
        return
      }
      row.isShowInput = false
    }

    // 属性值修改
    const toEditAttrValue=(row:AttrValueInfoModel,index: number)=>{
     
      
      row.isShowInput = true,
      nextTick(()=>{
        inputRef.value[index].focus()
      })
    }

    // 删除属性
    const confirmEventAttrValue =(index:number)=>{
      attrInfo.attrValueList.splice(index,1)
    }

    // 添加新属性时清空旧值
    const toSaveAttrValue = ()=>{
      isShowAttrList.value = false
      //清空旧值
      attrInfo.attrName =''
      attrInfo.attrValueList=[]
      delete attrInfo.id
    }

    //单击保存，添加属性
    const saveAttrInfo = async ()=>{
      attrInfo.categoryId = categoryStore.category3Id as number
      await reqAddOrUpdateAttrInfo(attrInfo)
      ElMessage.success('属性添加成功')
      //跳转到列表页
      isShowAttrList.value = true
      // 重新获取页面
      getAttrListData()
    }

    //点击编辑按钮，跳转到添加属性页面
    const toEditAttr=(row:AttrInfoModel)=>{
      isShowAttrList.value = false
      Object.assign(attrInfo,row)
    }


</script>

<style scoped></style>
